﻿using System;
using System.Linq;
using EPiBoost.Core.Infrastructure.Interfaces.Providers;
using EPiBoost.Core.Infrastructure.Providers;
using EPiServer.PlugIn;

namespace EPiBoost.Core.Plugins.Gui.Admin
{
		[GuiPlugIn(DisplayName = "EPiBoost - View 404 Exceptions", Description = "Shows the latest 404 Exceptions", 
			Area = PlugInArea.AdminMenu, Url = RegisterResources.FilePathView404Exceptions)]
    public partial class Viewe404Exceptions : System.Web.UI.Page
    {
	    protected void Page_Load(object sender, EventArgs e)
	    {
		    IExceptionLogProvider logger = new ExceptionLogProvider();
		    var logs = logger.GetLogs().Where(x => x.HttpStatusCode == 404);

		    var groupedLogs = logs.GroupBy(x => x.Uri).Select(x => new
			    {
				    Uri = x.Key,
				    Count = x.Count(),
				    LatestDate = x.Max(y => y.LogDate)
			    }).OrderByDescending(x => x.Count);

				rptErrors.DataSource = groupedLogs;
		    rptErrors.DataBind();

				if (Request["details"] != null)
				{
					var detailUrl = Server.UrlDecode(Request["details"]);
					ltlDetailUrl.Text = detailUrl;

					var inbound = logs.Where(x => x.Uri.ToLower() == detailUrl).Select(x=>x.UrlReferrer ?? "Direct").Distinct().ToList();
					rptInbound.DataSource = inbound;
					rptInbound.DataBind();

					plhDetails.Visible = true;
				}


	    }
    }
}